﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ArithmeticExpressionCalculator
{
    class ArithmeticExpressionCalculator : IExpressionCalculator
    {
        int position;
        int last_pos;
        int str_lenght_before_exchange;
        string str;
        DifficultExpression dExpr;
        public ArithmeticExpressionCalculator()
        {
            position = last_pos = str_lenght_before_exchange = 0;
            str = "";
            dExpr = new DifficultExpression();
        }
        private string GetExpressionWithoutNesting()
        {
            position = last_pos = 0;
            string part = "";
            while (position <= str.Length - 1)
            {
                if (str[position] == '(')
                {
                    last_pos = position;
                    position++;
                }
                else
                    if (str[position] == ')')
                    {
                        part = str.Substring(last_pos + 1, position - last_pos - 1);
                        break;
                    }
                    else
                        position++;
            }
            if (position == str.Length) position--;
            if (last_pos == 0 && position == str.Length - 1 && part == "")
                part = String.Copy(str);
            return part;
        }
        public double Execute(string str)
        {
            double result;
            do
            {
                this.str = str;
                string expression_string = GetExpressionWithoutNesting();
                result = dExpr.Execute(expression_string);
                CorrectValueInsert cvi = new CorrectValueInsert(str, result);
                str_lenght_before_exchange = str.Length;
                str = cvi.Exchange(last_pos, position);
            } while (last_pos != 0 || position != str_lenght_before_exchange - 1);
            return result;
        }
    }
}
